import React, { useRef, useEffect, useState } from 'react';
import styles from './index.module.less';
import ButtonFooter from '@/components/button-footer';
import FormGroup, { FormListItem } from '@/components/form-group';
import { AddOutsideUser, GetOutsideUserDetail, EditOutsideUser } from '@/services/member';
import moment from 'moment';
// import { district } from 'antd-mobile-v2-demo-data';
import { Toast } from 'antd-mobile-v2';
import {
  SEX_LIST, SEX_LIST_OUTSIDE, RESIDENT_TYPE_LIST, PEOPLE_STATUS_LIST, ENJAMBMENT_TYPE_LIST, PAYLOCATION_TYPE_LIST, ISHAVE
} from '@/pages/member/constants';
import { clearRouteBlocker, setRouteBlocker } from '@/components/form-group/route-blocker';
import { Prompt } from 'react-router-dom';
import { GetProvince, GetCities, GetAreas, GetOccupationCode, GetCardTypeCode, GetCountryCode, GetBankArea, GetBanks } from '@/services/commons';
import { CheckDateTime } from '@/utils';

const CreateMember: React.FC<any> = (props) => {
  const formRef: React.MutableRefObject<any> = useRef();
  const memberId = useRef(props.match.params.id);
  // 省市信息
  const [provinceOptions, setProvinceOptions] = useState<any[]>([]);
  const [provinceId, setProvinceId] = useState<string>();
  const [cityOptions, setCityOptions] = useState<any[]>([]);
  const [cityId, setCityId] = useState<string>();
  const [areaOptions, setAreaOptions] = useState<any[]>([]);
  const [areaId, setAreaId] = useState<string>();

  const [occupationCode, setOccupationCode] = useState<any[]>([]);
  const [cardTypeOption, setCardTypeOption] = useState<any[]>([]);
  const [countryCode, setCountryCode] = useState<any[]>([]);
  const [bankAreaOptions, setBankAreaOptions] = useState<any[]>();
  const [bankAreaId, setbankAreaId] = useState<string>();
  const [bankOptions, setBankOptions] = useState<any[]>();
  const [isEnjambmentVal, setIsEnjambmentVal] = useState<number>(0);
  const [cardId, setCardId] = useState<string>('3');
  const checkCardCode = (_rule: any, value: any, callback: any) => {
    // const cardTypeCode = formRef.current.getData()['cardTypeCode'];
    // if (!cardTypeCode) return callback('证件号为空');
    const reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
    if (cardId === '3' && value && !reg.test(value)) {
      return callback('证件号格式错误');
    }
    return callback();
  };

  // 判断银行卡号长度是否符合标准
  const checkCardLength = (_rule: any, value: any, callback: any) => {
    if (value === undefined) return callback();
    const params = value.replace(/\s/g, '');
    const reg = /^.{7,30}$/;
    if (value && !reg.test(params)) {
      return callback('银行卡号需为7-30位');
    }
    return callback();
  };

  const getList = () => {

    let applyBankPlaceholder = '请选择（选填）';
    if (!bankAreaId) {
      applyBankPlaceholder = '请先选择开户行所属地区';
    } else {
      if (!isEnjambmentVal) {
        applyBankPlaceholder = '请选择（选填）';
      } else {
        applyBankPlaceholder = '请选择';
      }
    }

    const formList: FormListItem[] = [
      {
        valueKey: 'baseInfo', label: '基本信息', type: 'title'
      }, {
        valueKey: 'cardTypeCode', label: '证件类型', type: 'picker',
        pickerOptions: cardTypeOption,
        options: { rules: [{ required: true, message: '请选择证件类型' }] },
        cellProps: {
          onChange: (val: string) => {
            formRef.current.resetValues(['cardCode']);
            setCardId(val[0]);
          }
        }
      },
      {
        valueKey: 'cardCode', label: '证件号', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入证件号' },
            { whitespace: true, message: '证件号不能为空' },
            { validator: cardId === '3' ? checkCardCode : '' },
            { pattern: /^[A-Za-z0-9]+$/, message: '证件号只能为数字和字母' }
          ]
        },
        cellProps: {
          maxLength: 18,
          onChange: (val: any) => {
            const birthday = val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14);
            const oldData = formRef?.current?.getData();
            if (CheckDateTime(birthday)) {
              birthday.length < 10 && formRef.current.setValues({ ...oldData, birthday: undefined });
              birthday.length === 10 && formRef?.current?.setValues({ ...oldData, birthday: moment(birthday) });
            } else {
              birthday.length < 10 && formRef.current.setValues({ ...oldData, birthday: undefined });
            }
            const _Data = formRef?.current?.getData();
            if (val.length >= 17) {
              if (parseInt(val.substr(16, 1)) % 2 == 1) {
                formRef?.current?.setValues({ ..._Data, sex: '1' });
              } else {
                formRef?.current?.setValues({ ..._Data, sex: '2' });
              }
            }
          }
        }
      }, {
        valueKey: 'chinaUserName', label: '姓名(中文)', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 64 }
      }, {
        valueKey: 'sex', label: '性别', type: 'picker',
        pickerOptions: SEX_LIST_OUTSIDE,
        options: { rules: [{ required: true, message: '请选择性别' }] },
        cellProps: { extra: '请选择' }
      }, {
        valueKey: 'birthday', label: '出生年月日', type: 'datePicker',
        options: { rules: [{ required: true, message: '请选择出生年月日' }] },
        cellProps: { extra: '请选择', minDate: new Date(1800, 1, 1, 0, 0, 0) }
      },
      // {
      //   valueKey: 'birthLocation', label: '出生地', type: 'picker',
      //   pickerOptions: district,
      //   options: { rules: [{ required: true, message: '请选择出生地' }] },
      //   cellProps: { cols: 3 }
      // },
      {
        valueKey: 'birthLocation', label: '出生地', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入出生地' },
            { whitespace: true, message: '出生地不能为空' }
          ]
        },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'nationality', label: '国籍/地区', type: 'picker',
        pickerOptions: countryCode,
        options: { rules: [{ required: true, message: '请选择国籍/地区' }] }
      }, {
        valueKey: 'resident', label: '是否居民', type: 'picker',
        pickerOptions: RESIDENT_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择是否居民' }] }
      }, {
        valueKey: 'mobile', label: '手机号', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入手机号' },
            { pattern: /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/, message: '手机号码格式错误' }
          ]
        },
        cellProps: { type: 'number', maxLength: 11 }
      }, {
        valueKey: 'occupationCode', label: '职业代码', type: 'picker',
        pickerOptions: occupationCode,
        options: { rules: [{ required: true, message: '请选择职业代码' }] }
      }, {
        valueKey: 'workUnit', label: '工作单位', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入工作单位' },
            { whitespace: true, message: '工作单位不能为空' }
          ]
        },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'peopleStatus', label: '人员状态', type: 'picker',
        pickerOptions: PEOPLE_STATUS_LIST,
        options: { rules: [{ required: true, message: '请选择人员状态' }] }
      }, {
        valueKey: 'email', label: 'Email', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 30 },
        options: {
          rules: [
            { whitespace: true, message: '请输入邮箱' },
            { pattern: /^([\S])+@[a-zA-Z0-9]+\.([a-zA-Z]+)$/, message: '邮箱格式错误' }
          ]
        }
      }, {
        valueKey: 'remarks', label: '备注', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 200 }
      }, {
        valueKey: 'countInfo', label: '账户信息', type: 'title'
      }, {
        valueKey: 'openAccountName', label: '开户姓名', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入开户姓名' },
            { whitespace: true, message: '开户姓名不能为空' }
          ]
        },
        cellProps: { maxLength: 64 }
      }, {
        valueKey: 'bankAccount', label: '银行卡号', type: 'input',
        options: {
          rules: [
            { required: true, message: '请输入银行卡号' },
            { validator: checkCardLength }
          ]
        },
        cellProps: { maxLength: 30 }
      }, {
        valueKey: 'isEnjambment', label: '是否跨行', type: 'picker',
        pickerOptions: ENJAMBMENT_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择是否跨行' }] },
        cellProps: {
          onChange: (val: string[]) => {
            formRef.current.resetValues(['applyBank']);
            setIsEnjambmentVal(Number(val[0]));
          }
        }
      }, {
        valueKey: 'regionName', label: '开户行所属地区', type: 'picker',
        options: { rules: [{ required: isEnjambmentVal ? true : false, message: '请选择开户行所属地区' }] },
        cellProps: {
          extra: isEnjambmentVal ? '请选择' : '请选择（选填）',
          onChange: (val: string) => {
            if (val != bankAreaId) {
              setbankAreaId(val[0]);
              formRef.current.resetValues(['applyBank']);
            }
          }
        },
        pickerOptions: bankAreaOptions
      }, {
        valueKey: 'applyBank', label: '开户行', type: 'picker',
        options: { rules: [{ required: isEnjambmentVal ? true : false, message: '请选择开户行' }] },
        pickerOptions: bankOptions,
        cellProps: {
          extra: applyBankPlaceholder, disabled: !bankAreaId
        }

      }, {
        valueKey: 'payLocation', label: '支付地', type: 'picker',
        pickerOptions: PAYLOCATION_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择支付地' }] }
      }, {
        valueKey: 'outsidePayLocation', label: '境外支付地', type: 'input',
        cellProps: { placeholder: '请输入（选填）', maxLength: 64 }
      }, {
        valueKey: 'otherInfo', label: '其他信息', type: 'title'
      }, {
        valueKey: 'employee', label: '是否雇员', type: 'picker',
        pickerOptions: ENJAMBMENT_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择是否雇员' }] }
      }, {
        valueKey: 'shareholder', label: '是否股东/投资者', type: 'picker',
        pickerOptions: ENJAMBMENT_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择是否股东/投资者' }] }
      }, {
        valueKey: 'special', label: '是否残疾烈属孤老', type: 'picker',
        pickerOptions: ENJAMBMENT_TYPE_LIST,
        options: { rules: [{ required: true, message: '请选择是否残疾烈属孤老' }] }
      }, {
        valueKey: 'house', label: '境内有无住所', type: 'picker',
        pickerOptions: ISHAVE,
        options: { rules: [{ required: true, message: '请选择境内有无居住' }] }
      }, {
        valueKey: 'firstToChinaTime', label: '首次入境时间', type: 'datePicker',
        cellProps: { extra: '请选择（选填）', minDate: new Date(1800, 1, 1, 0, 0, 0) }
      }, {
        valueKey: 'entryTime', label: '本年入境时间', type: 'datePicker',
        cellProps: { extra: '请选择（选填）', minDate: new Date(1800, 1, 1, 0, 0, 0) }
      }, {
        valueKey: 'toChinaTime', label: '来华时间', type: 'datePicker',
        cellProps: { extra: '请选择（选填）', minDate: new Date(1800, 1, 1, 0, 0, 0) }
      }, {
        valueKey: 'estimatedLeaveTime', label: '预计离境时间', type: 'datePicker',
        cellProps: { extra: '请选择（选填）', minDate: new Date(1800, 1, 1, 0, 0, 0) }
      }, {
        valueKey: 'residentialProvince', label: '居住省份', type: 'picker',
        pickerOptions: provinceOptions,
        cellProps: {
          extra: '请选择（选填）',
          onChange: (val: string) => {
            if (val != provinceId) {
              setCityId(undefined);
              setAreaId(undefined);
              formRef.current.resetValues(['residentialCity', 'residentialArea']);
              formRef.current.setValues({
                residentialAddress: undefined
              });
              setProvinceId(val);
            }
          }
        }
      }, {
        valueKey: 'residentialCity', label: '居住城市', type: 'picker',
        pickerOptions: cityOptions,
        cellProps: {
          disabled: !provinceId,
          extra: !provinceId ? '请先选择居住省份' : '请选择（选填）',
          onChange: (val: string) => {
            if (val != cityId) {
              setAreaId(undefined);
              formRef.current.resetValues(['residentialArea']);
              formRef.current.setValues({
                residentialAddress: undefined
              });
              setCityId(val);
            }
          }
        }
      }, {
        valueKey: 'residentialArea', label: '居住所在区县', type: 'picker',
        pickerOptions: areaOptions,
        cellProps: {
          disabled: !cityId,
          extra: !cityId ? '请先选择居住城市' : '请选择（选填）',
          onChange: (val: string) => {
            formRef.current.setValues({ residentialAddress: undefined });
            setAreaId(val);
          }
        }
      }, {
        valueKey: 'residentialAddress', label: '居住详细地址', type: 'input',
        cellProps: {
          disabled: !areaId,
          placeholder: !areaId ? '请先选择居住所在区县' : '请输入（选填）',
          maxLength: 64
        }
      }
    ];
    return formList;
  };

  const handleAddMember = async () => {
    const data = await formRef.current.getValues();
    const formateData = {
      ...data,
      cardTypeCode: data.cardTypeCode?.[0],
      peopleStatus: data.peopleStatus?.[0],
      resident: data.resident?.[0],
      sex: data.sex?.[0],
      nationality: data.nationality?.[0],
      occupationCode: data.occupationCode?.[0],
      // birthLocation: data.birthLocation?.[data.birthLocation.length - 1],
      birthday: data.birthday ? moment(data.birthday).format('YYYY-MM-DD') : undefined,
      isEnjambment: data.isEnjambment?.[0],
      region: data.regionName?.[0],
      payLocation: data.payLocation?.[0],
      outsidePayLocation: data.outsidePayLocation?.[0],
      employee: data.employee?.[0],
      shareholder: data.shareholder?.[0],
      special: data.special?.[0],
      house: data.house?.[0],
      firstToChinaTime: data.firstToChinaTime ? moment(data.firstToChinaTime).format('YYYY-MM-DD') : undefined,
      entryTime: data.entryTime ? moment(data.entryTime).format('YYYY-MM-DD') : undefined,
      toChinaTime: data.toChinaTime ? moment(data.toChinaTime).format('YYYY-MM-DD') : undefined,
      estimatedLeaveTime: data.estimatedLeaveTime ? moment(data.estimatedLeaveTime).format('YYYY-MM-DD') : undefined,
      residentialProvince: data.residentialProvince?.[0],
      residentialCity: data.residentialCity?.[0] || '',
      residentialArea: data.residentialArea?.[0] || '',
      applyBank: data.applyBank?.[0],
      residentialAddress: data.residentialAddress || ''
    };
    if (!data.occupationCode?.[0]) {
      Toast.fail('职业代码不能为空');
      return;
    }
    let AjaxRequest = AddOutsideUser;
    let successToast = '添加人员信息成功';
    if (memberId.current) {
      AjaxRequest = EditOutsideUser;
      formateData.id = memberId.current;
      successToast = '修改人员信息成功';
    }
    const res = await AjaxRequest(formateData);
    if (res.status === 200) {
      Toast.success(successToast);
      clearRouteBlocker();
      props.history.replace('/member');
    }
  };

  const getButtonOptions = () => (
    [
      {
        text: '保存',
        onClick: handleAddMember
      }
    ]
  );

  const getDetail = async () => {
    let info = {};
    //创建时设置默认值
    if (!memberId.current) {
      info = {
        cardTypeCode: cardTypeOption.length > 0 ? '3' : undefined,
        nationality: '001',
        resident: '01',
        peopleStatus: '1',
        isEnjambment: '0',
        payLocation: '1',
        employee: '0',
        shareholder: '0',
        special: '0',
        house: '0'
      };
    } else {
      const res = await GetOutsideUserDetail(memberId.current);
      if (res.status !== 200) {
        return Toast.fail('获取人员信息失败');
      }
      const data = res.data;

      setProvinceId(data.residentialProvince);
      setCityId(data.residentialCity);
      setAreaId(data.residentialArea);
      setbankAreaId(data.regionName);
      setCardId(data.cardTypeCode);
      info = {
        ...data,
        birthday: data.birthday ? moment(data.birthday, 'YYYY-MM-DD').toDate() : undefined,
        entryTime: data.entryTime ? moment(data.entryTime, 'YYYY-MM-DD').toDate() : undefined,
        estimatedLeaveTime: data.estimatedLeaveTime ? moment(data.estimatedLeaveTime, 'YYYY-MM-DD').toDate() : undefined,
        firstToChinaTime: data.firstToChinaTime ? moment(data.firstToChinaTime, 'YYYY-MM-DD').toDate() : undefined,
        toChinaTime: data.toChinaTime ? moment(data.toChinaTime, 'YYYY-MM-DD').toDate() : undefined
      };
    }
    console.log(info);

    formRef.current.setValues(info);
  };
  useEffect(() => {
    getDetail();
  }, [cardTypeOption]); //防止先显示默认值再回显value


  //获取省
  useEffect(() => {
    const getProvince = async () => {
      const data = await GetProvince();
      setProvinceOptions(data);
    };
    getProvince();
  }, []);
  //获取市
  useEffect(() => {
    if (!provinceId) {
      setCityOptions([]);
      return;
    }
    const getCities = async () => {
      const data = await GetCities(provinceId);
      setCityOptions(data);
    };
    getCities();
  }, [provinceId]);
  //获取区
  useEffect(() => {
    if (!cityId) {
      setAreaOptions([]);
      return;
    }
    const getAreas = async () => {
      const data = await GetAreas(cityId);
      setAreaOptions(data);
    };
    getAreas();
  }, [cityId]);
  //获取开户行
  useEffect(() => {
    if (!bankAreaId) {
      setBankOptions([]);
      return;
    }
    const getBanks = async () => {
      const data = await GetBanks(bankAreaId);
      setBankOptions(data);
    };
    getBanks();
  }, [bankAreaId]);



  /**
  * getOccupationCode 获取职业代码
  * getCardTypeCode 获取证件类型
  * getCountryCode 获取国家
  * getBankArea  获取开户行地区
 */
  useEffect(() => {
    const getOccupationCode = async () => {
      const data = await GetOccupationCode();
      setOccupationCode(data);
    };
    const getCardTypeCode = async () => {
      const data = await GetCardTypeCode();
      setCardTypeOption(data);
    };
    const getCountryCode = async () => {
      const data = await GetCountryCode();
      setCountryCode(data);
    };
    const getBankArea = async () => {
      const data = await GetBankArea();
      setBankAreaOptions(data);
    };
    getOccupationCode();
    getCardTypeCode();
    getCountryCode();
    getBankArea();
  }, []);


  return (
    <div className={styles.wrap}>
      <FormGroup
        routeBlock
        ref={formRef}
        formList={getList()}
      />
      <ButtonFooter data={getButtonOptions()} />
      <Prompt message={(nextRoute) => setRouteBlocker(props.history, nextRoute)} />
    </div>
  );
};

export default CreateMember;